<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import { notification } from 'ant-design-vue'
import type { ProductModel } from '@/api/product/product-list.ts'
import { createProductInfo, updateProductInfo } from '@/api/product/product-list.ts'

const emit = defineEmits(['cancel', 'ok'])

const isUpdate = ref(false)

const visible = ref(false)

const title = computed(() => {
  return isUpdate.value ? '编辑' : '新增'
})

const formRef = ref<FormInstance>()

const formData = ref<ProductModel>({
  productName: undefined,
  productDesc: undefined,
})

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

function open(record?: ProductModel) {
  visible.value = true
  isUpdate.value = !!record?.productId
  formData.value = cloneDeep(record) ?? {
    productName: '',
    productDesc: '',
  }
}

async function handleOk() {
  try {
    await formRef.value?.validate()
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value) {
      const res = await updateProductInfo(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
    else {
      console.log(formData.value)
      // 进入新增接口
      const res = await createProductInfo(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  }
  catch (errorInfo) {
    console.log('Form Validate Failed:', errorInfo)
  }
}

function handleCancel() {
  formRef.value?.resetFields()
  emit('cancel')
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" :title="title" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item name="productName" label="产品名称" :rules="[{ required: true, message: '请输入产品名称' }]">
        <a-input v-model:value="formData.productName" :maxlength="50" placeholder="请输入产品名称" />
      </a-form-item>
      <a-form-item name="productDesc" label="产品描述" :rules="[{ required: false, message: '请输入产品描述' }]">
        <a-input v-model:value="formData.productDesc" :maxlength="50" placeholder="请输入产品描述" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
